//
//  DetailDescription.m
//

#import "GTSummaryCell.h"
#import "UIKit+GTExtensions.h"

@interface GTSummaryCell ()
@property(nonatomic, retain) UILabel *label;
- (NSInteger)numberOfPrintedLinesForString:(NSString*)aString;
@end

@implementation GTSummaryCell
@synthesize label;

+ (id)cellForTableView:(UITableView*)aTableView font:(UIFont*)aFont numOfLines:(NSInteger)aNumOfLines reuseIdentifier:(NSString *)reuseIdentifier {
  GTSummaryCell *cell = (GTSummaryCell *)[aTableView dequeueReusableCellWithIdentifier:reuseIdentifier];
  if (cell == nil) {
    cell = [[[GTSummaryCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier] autorelease];
    cell.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin;
    cell.label = [[[UILabel alloc] initWithFrame:CGRectMake(25.0, 20.0, 260.0, (aFont.capHeight + 14)*aNumOfLines)] autorelease];
    cell.label.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin;
    cell.label.backgroundColor = [UIColor clearColor];
    cell.label.numberOfLines = aNumOfLines;
    cell.label.textAlignment = UITextAlignmentLeft;
    cell.label.lineBreakMode = UILineBreakModeTailTruncation;
    [cell addSubview:cell.label];

    CGRect cellFrame = cell.frame;
    cellFrame.size.height = cell.label.frame.size.height + 40;
    cell.frame = cellFrame;
  }
  return cell;
}

- (void)dealloc {
  [label release];
  [super dealloc];
}

- (void)showText:(NSString*)aString {
  label.text = aString;
  
  if ([self numberOfPrintedLinesForString:aString] <= label.numberOfLines) {
    self.accessoryType = UITableViewCellAccessoryNone;
    self.selectionStyle = UITableViewCellSelectionStyleNone;
  }
  else {
    self.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    self.selectionStyle = UITableViewCellSelectionStyleBlue;
  }
}

- (NSInteger)numberOfPrintedLinesForString:(NSString*)aString {
  NSInteger count = 0;
  for (NSString *line in [aString componentsSeparatedByString:@"\n"]) {
    count += (1 + [line length]/30);
  }
  return count;
}

@end
